var httpRequest = function (url, method, body, callback) {
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", function () {
        if (typeof(callback) === "function")
            callback(JSON.parse(xhr.responseText));
    });
    xhr.open(method, url);
    xhr.setRequestHeader("Content-Type", "application/json");
    if (typeof(body) !== "undefined" && body !== null)
        xhr.send(JSON.stringify(body));
    else
        xhr.send();
};

var getRequest = function (url, callback) {
    httpRequest(url, "GET", null, callback);
};

var postRequest = function (url, body, callback) {
    httpRequest(url, "POST", body, callback);
};

var putRequest = function (url, body, callback) {
    httpRequest(url, "PUT", body, callback);
};

var addNewElement = function (item) {
    var li = document.createElement('li');
    var label = document.createElement('label');
    var input = document.createElement('input');
    input.type = "checkbox";
    input.checked = item.completed;
    var innerTXT = document.createTextNode(item.name);
    li._trackId = item.id;
    label.appendChild(input);
    label.appendChild(innerTXT);
    li.appendChild(label);
    document.getElementById('aa').appendChild(li);
    if (input.checked) {
        label.classList.add("selected");
    }
    //li 添加事件
    input.addEventListener('change', function () {
        //alert('修改前的completed属性'+item_send[0].completed);
        item.completed = !item.completed;
        putRequest("/api/items/" + item.id, item);
        //alert(this.firstChild.childNodes[0]); 
        /*var li_input = this;
        var li_label = this.parentNode;*/
        if (input.checked) {
            label.classList.add("selected");
        }
        else {
            label.classList.remove("selected");
        }
    }, false);
};

//创建一个数组存放获取的items
var items = new Array();

//GET获取数据
getRequest("/api/items", function (getobj) {
    items = getobj;
    //alert(items[1].id);
    for (i = 0; i < getobj.length; i++) {
        addNewElement(getobj[i]);
    }
});

//点击 触发增加事件
var add = function () {
    //发送请求
    var inputTXT = document.getElementById('input').value;
    if (inputTXT == "") {
        inputTXT = prompt('Please input something!');
    }
    var item = {
        name: inputTXT,
        completed: false
    };
    postRequest("/api/items", item, function (postobj) {
        //alert(items.length);
        items.push(postobj);
        //alert(postobj[0]);
        addNewElement(postobj);
    });
}
document.getElementById('add').addEventListener('click', add, false);
